package controller

import (
	"ginfast/api/mall/dto"
	"ginfast/api/mall/model"
	"ginfast/pkg/dao"
	"ginfast/pkg/gctx"

	"github.com/gin-gonic/gin"
)

// UserAddress 地址
type UserAddress struct {
}

// ListHandler 列表
func (o *UserAddress) ListHandler(c *gin.Context) {
	var data []model.UserAddress
	if err := dao.DbFind(&data); err != nil {
		gctx.JSONWriteError(err, c)
		return
	}
	gctx.JSONWriteData(data, c)
}

// PageHandler 分页
func (o *UserAddress) PageHandler(c *gin.Context) {
	var p dto.Where
	if err := c.ShouldBind(&p); err != nil {
		gctx.JSONWriteError(err, c)
		return
	}
	var data []model.UserAddress
	total, _ := p.DbModelWhere(&model.UserAddress{}).Find(&data)
	gctx.JSONWrite(gin.H{"total": total, "rows": data}, c)
}

// GetHandler 查询
func (o *UserAddress) GetHandler(c *gin.Context) {
	dao.QueryByID(&model.UserAddress{}, c)
}

// AddHandler 新增
func (o *UserAddress) AddHandler(c *gin.Context) {
	var p model.UserAddress
	//获取参数
	if err := c.ShouldBind(&p.UserAddressOpt); err != nil {
		gctx.JSONWriteError(err, c)
		return
	}
	if err := dao.DbCreate(&p); err != nil {
		gctx.JSONWriteError(err, c)
		return
	}
	gctx.JSONOK(c)
}

// UpdateHandler 修改
func (o *UserAddress) UpdateHandler(c *gin.Context) {
	var p model.UserAddress
	//获取参数
	if err := c.ShouldBind(&p.UserAddressOpt); err != nil {
		gctx.JSONWriteError(err, c)
		return
	}
	if err := dao.DbUpdateModel(&p); err != nil {
		gctx.JSONWriteError(err, c)
		return
	}
	gctx.JSONOK(c)
}

// DeleteHandler 删除
func (o *UserAddress) DeleteHandler(c *gin.Context) {
	dao.Deletes(&model.UserAddress{}, c)
}

// UpdateStatusHandler 修改
func (o *UserAddress) UpdateDefaultHandler(c *gin.Context) {
	var p model.UserAddress
	//获取参数
	if err := c.ShouldBind(&p.UserAddressOpt); err != nil {
		gctx.JSONWriteError(err, c)
		return
	}
	if err := dao.DbUpdateColById(&model.UserAddress{}, p.ID, "is_default", p.IsDefault); err != nil {
		gctx.JSONWriteError(err, c)
		return
	}
	gctx.JSONOK(c)
}

func (o UserAddress) Routers(r *gin.RouterGroup) {
	r.GET("/list", o.ListHandler)
	r.GET("/page", o.PageHandler)
	r.GET("/:id", o.GetHandler)
	r.POST("", o.AddHandler)
	r.PUT("", o.UpdateHandler)
	r.PUT("/default", o.UpdateDefaultHandler)
}
